'''
Description: ：文件请求监听器模块
Author: HowsenFisher
Date: 2021-04-08 17:25:55
LastEditTime: 2021-04-11 00:53:21
LastEditors: liutq
Reference: 
'''
import socket
from Config import conf
from NetTools.FileSender import FileSender
from threading import Thread

class FileRequestListener:
    '''
    @description: 文件请求监听器类
    @param  {*}
    @return {*}
    @param {*} self
    @param {*} parent
    '''
    def __init__(self,parent):
        # 父对象
        self.parent = parent
        # 打印info
        self.parent.newInfoSignal.emit("文件请求监听器初始化")
        # 创建socket TCP
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # 打印info
        self.parent.newInfoSignal.emit("文件请求监听器绑定端口:%d"%conf.file_control_port)
        # 绑定本机文件请求（控制）端口
        self.s.bind((conf.ip,conf.file_control_port))
        # 等待队列最长255
        self.s.listen(255)
        count = 0
        while True:
            # 接受一个文件请求连接，获取对方socket对象和地址
            client,clientAddr = self.s.accept()
            # 打印info
            self.parent.newInfoSignal.emit("文件请求监听器:检测到了一个来自%s连接,开始检测请求"%clientAddr[0])
            # 创建检测文件请求线程
            self.listenThread = Thread(target=lambda:self.listen(client,clientAddr,count))
            # 线程开始
            self.listenThread.start()
            count+=1
    
    '''
    @description: 检测文件请求函数
    @param  {*}
    @return {*}
    @param {*} self
    @param {*} client：对方socket对象
    @param {*} clientAddr：对方地址
    @param {*} count：debug用，无实际意义
    '''
    def listen(self,client,clientAddr,count):
        while True:
            # 接收数据
            data = client.recv(1024).decode("utf-8")
            # 如果收到不是空串并且是文件请求命令
            if not data=="" and data.split(":")[0]=="fileReq":
                # 提取对方想要获取的文件路径
                filepath = conf.share_dir+"/"+data.split(":")[1]
                # 对方IP
                dst_ip = clientAddr[0]#(ip,port)
                # 打印info
                self.parent.newInfoSignal.emit("文件请求监听器:收到一个来自%s的对文件%s请求"%(dst_ip,filepath))
                # 创建一个文件发送线程
                FileSendThread = Thread(target=lambda:FileSender(self.parent,dst_ip,conf.file_port,filepath,count))
                # 线程开始
                FileSendThread.start()
                break


